package com.example.mq.demo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WHY
 * Date: 2023-09-15
 * Time: 20:56
 */

import com.example.mq.common.Consumer;
import com.example.mq.common.MqException;
import com.example.mq.mqclient.Channel;
import com.example.mq.mqclient.Connection;
import com.example.mq.mqclient.ConnectionFactory;
import com.example.mq.mqsever.core.BasicProperties;
import com.example.mq.mqsever.core.Exchangetype;
import org.springframework.ui.context.Theme;
import org.yaml.snakeyaml.tokens.BlockEndToken;

import java.io.IOException;

/**
 * 这是一个消费者
 * 通常也是一个单独的服务器来执行
 */
public class DemoConsumer {
    public static void main(String[] args) throws IOException, MqException, InterruptedException {
        System.out.println("启动消费者!");
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(9090);


        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();

        channel.exchangeDeclare("testExchange", Exchangetype.DIRECT,true,false,null);
        channel.queueDeclare("testQueue",true,false,false,null);


        channel.basicConsume("testQueue", true, new Consumer() {
            @Override
            public void handlerDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException, ClassNotFoundException {
                System.out.println("[消费数据] 开始!");
                System.out.println("consumerTag="+consumerTag);
                System.out.println("basicProperties="+basicProperties);
                String bodyString=new String(body,0,body.length);
                System.out.println("body="+bodyString);
                System.out.println("[消费数据]结束!");
            }
        });


        //由于消费者不知道生产者会生产多少,就通过这个循环模拟一直等待消费
        while(true){
            Thread.sleep(500);
        }

    }

}
